<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>实践一下--MyBatisPlus | Celts</title><meta name="author" content="PaulGeorge"><meta name="copyright" content="PaulGeorge"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="实践是检验真理的唯一标准  本篇着重介绍一下 MyBatisPlus      写在前面 忙里偷闲，趁着有时间来写一篇关于 MybatisPlus 的学习笔记！ 其实官网上的 API 很全面，不会的就去官网上查一查~ MyBatisPlus官网">
<meta property="og:type" content="article">
<meta property="og:title" content="实践一下--MyBatisPlus">
<meta property="og:url" content="https://curry3035.gitee.io/posts/51171/index.html">
<meta property="og:site_name" content="Celts">
<meta property="og:description" content="实践是检验真理的唯一标准  本篇着重介绍一下 MyBatisPlus      写在前面 忙里偷闲，趁着有时间来写一篇关于 MybatisPlus 的学习笔记！ 其实官网上的 API 很全面，不会的就去官网上查一查~ MyBatisPlus官网">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://curry3035.gitee.io/img/avatar.jpg">
<meta property="article:published_time" content="2021-08-14T13:00:00.000Z">
<meta property="article:modified_time" content="2022-05-26T18:18:39.138Z">
<meta property="article:author" content="PaulGeorge">
<meta property="article:tag" content="MyBatis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://curry3035.gitee.io/img/avatar.jpg"><link rel="shortcut icon" href="/img/ic.ico"><link rel="canonical" href="https://curry3035.gitee.io/posts/51171/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":false,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: PaulGeorge","link":"链接: ","source":"来源: Celts","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '实践一下--MyBatisPlus',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-27 02:18:39'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/background.css"><link rel="stylesheet" href="/css/my.css"><meta name="generator" content="Hexo 5.4.2"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Celts"><span class="site-name">Celts</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">实践一下--MyBatisPlus</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-08-14T13:00:00.000Z" title="发表于 2021-08-14 21:00:00">2021-08-14</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-26T18:18:39.138Z" title="更新于 2022-05-27 02:18:39">2022-05-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%A1%86%E6%9E%B6/">框架</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">5.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>24分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="实践一下--MyBatisPlus"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>实践是检验真理的唯一标准</p>
</blockquote>
<p><strong>本篇着重介绍一下 MyBatisPlus</strong></p>
<hr>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/logo.svg" style="zoom:30%;" />



<p><strong>写在前面</strong></p>
<p>忙里偷闲，趁着有时间来写一篇关于 MybatisPlus 的学习笔记！</p>
<p>其实官网上的 API 很全面，不会的就去官网上查一查~</p>
<p><a target="_blank" rel="noopener" href="https://baomidou.com/">MyBatisPlus官网</a></p>
<span id="more"></span>



<h2 id="MyBatisPlus-简介"><a href="#MyBatisPlus-简介" class="headerlink" title="MyBatisPlus  简介"></a>MyBatisPlus  简介</h2><h3 id="特性"><a href="#特性" class="headerlink" title="特性"></a>特性</h3><ul>
<li><strong>无侵入</strong>：只做增强不做改变，引入它不会对现有工程产生影响，如丝般顺滑</li>
<li><strong>损耗小</strong>：启动即会自动注入基本 CURD，性能基本无损耗，直接面向对象操作</li>
<li><strong>强大的 CRUD 操作</strong>：内置通用 Mapper、通用 Service，仅仅通过少量配置即可实现单表大部分 CRUD 操作，更有强大的条件构造器，满足各类使用需求</li>
<li><strong>支持 Lambda 形式调用</strong>：通过 Lambda 表达式，方便的编写各类查询条件，无需再担心字段写错</li>
<li><strong>支持主键自动生成</strong>：支持多达 4 种主键策略（内含分布式唯一 ID 生成器 - Sequence），可自由配置，完美解决主键问题</li>
<li><strong>支持 ActiveRecord 模式</strong>：支持 ActiveRecord 形式调用，实体类只需继承 Model 类即可进行强大的 CRUD 操作</li>
<li><strong>支持自定义全局通用操作</strong>：支持全局通用方法注入（ Write once, use anywhere ）</li>
<li><strong>内置代码生成器</strong>：采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码，支持模板引擎，更有超多自定义配置等您来使用</li>
<li><strong>内置分页插件</strong>：基于 MyBatis 物理分页，开发者无需关心具体操作，配置好插件之后，写分页等同于普通 List 查询</li>
<li><strong>分页插件支持多种数据库</strong>：支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库</li>
<li><strong>内置性能分析插件</strong>：可输出 SQL 语句以及其执行时间，建议开发测试时启用该功能，能快速揪出慢查询</li>
<li><strong>内置全局拦截插件</strong>：提供全表 delete 、 update 操作智能分析阻断，也可自定义拦截规则，预防误操作</li>
</ul>
<h3 id="框架结构"><a href="#框架结构" class="headerlink" title="框架结构"></a>框架结构</h3><p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/mybatis-plus-framework.jpg"></p>
<hr>
<h2 id="MyBatisPlus-快速入门"><a href="#MyBatisPlus-快速入门" class="headerlink" title="MyBatisPlus  快速入门"></a>MyBatisPlus  快速入门</h2><h3 id="简单的-Demo-实现"><a href="#简单的-Demo-实现" class="headerlink" title="简单的 Demo 实现"></a>简单的 Demo 实现</h3><h4 id="数据库中创建-User-表"><a href="#数据库中创建-User-表" class="headerlink" title="数据库中创建 User 表"></a>数据库中创建 User 表</h4><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">DROP TABLE IF EXISTS user;</span><br><span class="line"></span><br><span class="line">CREATE TABLE user</span><br><span class="line">(</span><br><span class="line">	id BIGINT(20) NOT NULL COMMENT &#x27;主键ID&#x27;,</span><br><span class="line">	name VARCHAR(30) NULL DEFAULT NULL COMMENT &#x27;姓名&#x27;,</span><br><span class="line">	age INT(11) NULL DEFAULT NULL COMMENT &#x27;年龄&#x27;,</span><br><span class="line">	email VARCHAR(50) NULL DEFAULT NULL COMMENT &#x27;邮箱&#x27;,</span><br><span class="line">	PRIMARY KEY (id)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">DELETE FROM user;</span><br><span class="line"></span><br><span class="line">INSERT INTO user (id, name, age, email) VALUES</span><br><span class="line">(1, &#x27;Jone&#x27;, 18, &#x27;test1@baomidou.com&#x27;),</span><br><span class="line">(2, &#x27;Jack&#x27;, 20, &#x27;test2@baomidou.com&#x27;),</span><br><span class="line">(3, &#x27;Tom&#x27;, 28, &#x27;test3@baomidou.com&#x27;),</span><br><span class="line">(4, &#x27;Sandy&#x27;, 21, &#x27;test4@baomidou.com&#x27;),</span><br><span class="line">(5, &#x27;Billie&#x27;, 24, &#x27;test5@baomidou.com&#x27;);</span><br></pre></td></tr></table></figure>



<h4 id="添加-mybatis-plus-依赖"><a href="#添加-mybatis-plus-依赖" class="headerlink" title="添加 mybatis-plus 依赖"></a>添加 mybatis-plus 依赖</h4><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.4.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意引入了<code>mybatisplus </code>就不要再引入<code>mybatis</code>的启动器了</p>
</blockquote>
<h4 id="编写-application-yml-文件"><a href="#编写-application-yml-文件" class="headerlink" title="编写 application.yml 文件"></a>编写 application.yml 文件</h4><figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">datasource:</span></span><br><span class="line">    <span class="attr">driver-class-name:</span> <span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:mysql://localhost:3306/mybatis-plus?serverTimezone=Asia/Shanghai&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;zeroDateTimeBehavior=convertToNull&amp;useSSL=false&amp;allowPublicKeyRetrieval=true</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">root</span></span><br><span class="line">    </span><br><span class="line"><span class="attr">mybatis-plus:</span></span><br><span class="line">  <span class="attr">configuration:</span></span><br><span class="line">    <span class="attr">map-underscore-to-camel-case:</span> <span class="literal">true</span></span><br><span class="line">    <span class="attr">auto-mapping-behavior:</span> <span class="string">full</span></span><br><span class="line">    <span class="attr">log-impl:</span> <span class="string">org.apache.ibatis.logging.stdout.StdOutImpl</span></span><br></pre></td></tr></table></figure>



<h4 id="创建实体类"><a href="#创建实体类" class="headerlink" title="创建实体类"></a>创建实体类</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@ToString</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="comment">//主键自增</span></span><br><span class="line">    <span class="meta">@TableId(type = IdType.AUTO)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line">    <span class="keyword">private</span> String email;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="创建-Mapper-接口"><a href="#创建-Mapper-接口" class="headerlink" title="创建 Mapper 接口"></a>创建 Mapper 接口</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Repository</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;User&gt; &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="添加扫描注解"><a href="#添加扫描注解" class="headerlink" title="添加扫描注解"></a>添加扫描注解</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="meta">@MapperScan(&quot;com.ase.mybatis.mapper&quot;)</span> <span class="comment">//更加的灵活</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MybatisApplication</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SpringApplication.run(MybatisApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="编写测试类"><a href="#编写测试类" class="headerlink" title="编写测试类"></a>编写测试类</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Log4j2</span></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="meta">@DisplayName(&quot;MybatisPlus 接口测试&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MybatisPlusTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="meta">@DisplayName(&quot;测试查询全部&quot;)</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">queryAllList</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;User&gt; userList = userMapper.selectList(<span class="literal">null</span>);</span><br><span class="line">        userList.forEach(user -&gt; log.info(user));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="meta">@DisplayName(&quot;测试插入一条数据&quot;)</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">saveUserOne</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        user.setName(<span class="string">&quot;Tom&quot;</span>);</span><br><span class="line">        user.setAge(<span class="number">23</span>);</span><br><span class="line">        user.setEmail(<span class="string">&quot;tom@163.com&quot;</span>);</span><br><span class="line">        <span class="comment">//插入的条数</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">insert</span> <span class="operator">=</span> userMapper.insert(user);</span><br><span class="line">        log.info(insert);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="service接口"><a href="#service接口" class="headerlink" title="service接口"></a>service接口</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserService</span> <span class="keyword">extends</span> <span class="title class_">IService</span>&lt;User&gt; &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="service实现类"><a href="#service实现类" class="headerlink" title="service实现类"></a>service实现类</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * service实现类 继承mybatisplus提供通用的service基类</span></span><br><span class="line"><span class="comment"> * ServiceImpl&lt;UserMapper, User&gt;</span></span><br><span class="line"><span class="comment"> *     2个泛型 ：</span></span><br><span class="line"><span class="comment"> *        第一个是Mapper接口</span></span><br><span class="line"><span class="comment"> *        第二个是对应实体类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserServiceImpl</span> <span class="keyword">extends</span> <span class="title class_">ServiceImpl</span>&lt;UserMapper, User&gt;<span class="keyword">implements</span> <span class="title class_">UserService</span> &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h3 id="常用注解"><a href="#常用注解" class="headerlink" title="常用注解"></a>常用注解</h3><h4 id="TableName"><a href="#TableName" class="headerlink" title="@TableName"></a>@TableName</h4><p>【映射数据库的表名，数据库表名为user】</p>
<ul>
<li><p>描述：用来将实体对象与数据库表名完成映射</p>
</li>
<li><p>修饰范围：作用在类上</p>
</li>
<li><p>常见属性： value：string类型，指定映射的表名</p>
</li>
</ul>
<h4 id="TableId"><a href="#TableId" class="headerlink" title="@TableId"></a>@TableId</h4><p>【数据库插入的id值默认为：全局的唯一id】</p>
<ul>
<li>描述：主键主键</li>
<li>修饰范围:用在属性上</li>
<li>常见属性：<ul>
<li>value：String类型，指定实体类中与表对应的主键列名</li>
<li>type：枚举类型，指定主键生成策略</li>
</ul>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//数据库ID自增</span></span><br><span class="line">AUTO(<span class="number">0</span>),</span><br><span class="line">NONE(<span class="number">1</span>),</span><br><span class="line"><span class="comment">//用户输入ID</span></span><br><span class="line">INPUT(<span class="number">2</span>),</span><br><span class="line">ASSIGN_ID(<span class="number">3</span>),</span><br><span class="line">ASSIGN_UUID(<span class="number">4</span>),</span><br><span class="line"></span><br><span class="line"><span class="comment">//后面3个被淘汰了</span></span><br><span class="line"><span class="comment">/** <span class="doctag">@deprecated</span> */</span></span><br><span class="line"><span class="meta">@Deprecated</span></span><br><span class="line">ID_WORKER(<span class="number">3</span>),</span><br><span class="line"><span class="comment">/** <span class="doctag">@deprecated</span> */</span></span><br><span class="line"><span class="meta">@Deprecated</span></span><br><span class="line">ID_WORKER_STR(<span class="number">3</span>),</span><br><span class="line"><span class="comment">/** <span class="doctag">@deprecated</span> */</span></span><br><span class="line"><span class="meta">@Deprecated</span></span><br><span class="line">UUID(<span class="number">4</span>);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>AUTO 默认就是数据库⾃增，开发者⽆需赋值，会主动回填。但是数据库的主键要有自增长 </p>
<p>ASSIGN_ID mybatisplus ⾃动赋值，雪花算法</p>
</blockquote>
<p><strong>全局ID生成策略</strong></p>
<p>在全局配置文件中，就不需要在每个pojo的主键上配置了</p>
<figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">mybatis-plus:</span></span><br><span class="line">  <span class="attr">global-config:</span></span><br><span class="line">    <span class="attr">db-config:</span></span><br><span class="line">      <span class="attr">id-type:</span> <span class="string">auto</span></span><br></pre></td></tr></table></figure>



<h4 id="TableField"><a href="#TableField" class="headerlink" title="@TableField"></a>@TableField</h4><ul>
<li>描述字段注解（非主键）</li>
<li>修饰范围:用在属性上</li>
</ul>
<h4 id="Version"><a href="#Version" class="headerlink" title="@Version"></a>@Version</h4><p>【标记乐观锁，通过 version 字段来保证数据的安全性，当修改数据的时候，会以 version 作为条件，当条件成立的时候才会修改成功】</p>
<p>举个荔枝：</p>
<p>version = 1</p>
<p>线程 1：update … set version = 2 where version = 1</p>
<p>线程2 ：update … set version = 2 where version = 1</p>
<p><strong>这样就只有一个线程会执行</strong></p>
<p><strong>乐观锁实现方式：</strong></p>
<ol>
<li>取出记录时，获取当前 version</li>
<li>更新时，带上这个 version</li>
<li>执行更新时， set version = newVersion where version = oldVersion</li>
<li>如果 version 不对，就更新失败</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="meta">@TableId(type =IdType.AUTO)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line">    <span class="keyword">private</span> String email;</span><br><span class="line">    <span class="meta">@Version</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> version;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注册配置类</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyBatisPlusConfig</span> &#123;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> MybatisPlusInterceptor <span class="title function_">mybatisPlusInterceptor</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">MybatisPlusInterceptor</span> <span class="variable">interceptor</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MybatisPlusInterceptor</span>();</span><br><span class="line">        interceptor.addInnerInterceptor(<span class="keyword">new</span> <span class="title class_">OptimisticLockerInnerInterceptor</span>());</span><br><span class="line">        <span class="keyword">return</span> interceptor;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="EnumValue"><a href="#EnumValue" class="headerlink" title="@EnumValue"></a>@EnumValue</h4><p>【通用枚举类注解，将数据库字段映射成实体类的枚举类型成员变量】</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> <span class="title class_">StatusEnum</span> &#123;</span><br><span class="line">    SUCCESS(<span class="number">200</span>,<span class="string">&quot;成功&quot;</span>),</span><br><span class="line">    FAILURE(<span class="number">300</span>,<span class="string">&quot;失败&quot;</span>);</span><br><span class="line">    <span class="meta">@EnumValue</span></span><br><span class="line">    <span class="keyword">private</span> Integer code;</span><br><span class="line">    <span class="keyword">private</span> String msg;</span><br><span class="line"></span><br><span class="line">    StatusEnum(Integer code, String msg) &#123;</span><br><span class="line">        <span class="built_in">this</span>.code = code;</span><br><span class="line">        <span class="built_in">this</span>.msg = msg;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="meta">@TableId(type =IdType.AUTO)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line">    <span class="keyword">private</span> String email;</span><br><span class="line">    <span class="keyword">private</span> Integer version;</span><br><span class="line">    <span class="keyword">private</span> StatusEnum status;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>application.yml</strong></p>
<figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">mybatis-plus:</span></span><br><span class="line">  <span class="attr">type-enums-package:</span> <span class="string">com.example.mybatisplus.enums</span></span><br></pre></td></tr></table></figure>



<h4 id="TableLogic"><a href="#TableLogic" class="headerlink" title="@TableLogic"></a>@TableLogic</h4><p>【映射逻辑删除】</p>
<table>
<thead>
<tr>
<th>属性</th>
<th>类型</th>
<th>必须指定</th>
<th>默认值</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>value</td>
<td>String</td>
<td>否</td>
<td>“”</td>
<td>逻辑未删除值</td>
</tr>
<tr>
<td>delval</td>
<td>String</td>
<td>否</td>
<td>“”</td>
<td>逻辑删除值</td>
</tr>
</tbody></table>
<p><strong>物理删除</strong>【在删除的时候直接将数据库的数据从数据库删除掉】</p>
<p><strong>逻辑删除</strong>【在逻辑层面控制删除，通常会在表里加入对应的逻辑删除标识字段，deleted，默认是有效的值为0，当用户删除时将数据修改为1.查询是只查询deleted=0的】</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="meta">@TableId(type =IdType.AUTO)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> AgeEnum age;</span><br><span class="line">    <span class="keyword">private</span> String email;</span><br><span class="line">    <span class="keyword">private</span> Integer version;</span><br><span class="line">    <span class="keyword">private</span> StatusEnum status;</span><br><span class="line">    <span class="meta">@TableLogic</span></span><br><span class="line">    <span class="keyword">private</span> Integer deleted;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>application.yml 添加配置</strong></p>
<figure class="highlight yml"><table><tr><td class="code"><pre><span class="line"><span class="attr">mybatis-plus:</span></span><br><span class="line">  <span class="attr">configuration:</span></span><br><span class="line">    <span class="attr">log-impl:</span> <span class="string">org.apache.ibatis.logging.stdout.StdOutImpl</span></span><br><span class="line">  <span class="attr">type-enums-package:</span> <span class="string">com.example.mybatisplus.enums</span></span><br><span class="line">  <span class="attr">global-config:</span></span><br><span class="line">    <span class="attr">db-config:</span></span><br><span class="line">      <span class="attr">logic-not-delete-value:</span> <span class="number">0</span></span><br><span class="line">      <span class="attr">logic-delete-value:</span> <span class="number">1</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>查询不会查询 deleted 为 1 的数据</p>
</blockquote>
<h4 id="OrderBy"><a href="#OrderBy" class="headerlink" title="@OrderBy"></a>@OrderBy</h4><p>【内置 SQL 默认指定排序，优先级低于 wrapper 条件查询】</p>
<table>
<thead>
<tr>
<th>属性</th>
<th>类型</th>
<th>必须指定</th>
<th>默认值</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>isDesc</td>
<td>boolean</td>
<td>否</td>
<td>true</td>
<td>是否倒序查询</td>
</tr>
<tr>
<td>delval</td>
<td>String</td>
<td>否</td>
<td>Short.MAX_VALUE</td>
<td>数字越小越靠前</td>
</tr>
</tbody></table>
<hr>
<h3 id="条件构造器"><a href="#条件构造器" class="headerlink" title="条件构造器"></a>条件构造器</h3><h4 id="wrapper"><a href="#wrapper" class="headerlink" title="wrapper"></a>wrapper</h4><p>【条件构造器】</p>
<ul>
<li>Wrapper ： 条件构造抽象类，最顶端父类</li>
<li>AbstractWrapper ： 用于查询条件封装，生成 sql 的 where 条件</li>
<li>QueryWrapper ： Entity 对象封装操作类，不是用lambda语法</li>
<li>UpdateWrapper ： Update 条件封装，用于Entity对象更新操作</li>
<li>AbstractLambdaWrapper ： Lambda 语法使用 Wrapper统一处理解析 lambda 获取 column。</li>
<li>LambdaQueryWrapper ：看名称也能明白就是用于Lambda语法使用的查询Wrapper</li>
<li>LambdaUpdateWrapper ： Lambda 更新封装Wrapper</li>
</ul>
<table>
<thead>
<tr>
<th align="center">函数名</th>
<th align="center">说明</th>
<th align="center">例子</th>
</tr>
</thead>
<tbody><tr>
<td align="center">eq</td>
<td align="center">等于 =</td>
<td align="center">eq(“name”, “老王”)—&gt;name = ‘老王’</td>
</tr>
<tr>
<td align="center">ne</td>
<td align="center">不等于 &lt;&gt;</td>
<td align="center">例: ne(“name”, “老王”)—&gt;name &lt;&gt; ‘老王’</td>
</tr>
<tr>
<td align="center">gt</td>
<td align="center">大于 &gt;</td>
<td align="center">gt(“age”, 18)—&gt;age &gt; 18</td>
</tr>
<tr>
<td align="center">ge</td>
<td align="center">大于等于 &gt;=</td>
<td align="center">ge(“age”, 18)—&gt;age &gt;= 18</td>
</tr>
<tr>
<td align="center">lt</td>
<td align="center">小于 &lt;</td>
<td align="center">lt(“age”, 18)—&gt;age &lt; 18</td>
</tr>
<tr>
<td align="center">le</td>
<td align="center">小于等于 &lt;=</td>
<td align="center">le(“age”, 18)—&gt;age &lt;= 18</td>
</tr>
<tr>
<td align="center">between</td>
<td align="center">BETWEEN 值1 AND 值2</td>
<td align="center">between(“age”, 18, 30)—&gt;age between 18 and 30</td>
</tr>
<tr>
<td align="center">notBetween</td>
<td align="center">NOT BETWEEN 值1 AND 值2</td>
<td align="center">notBetween(“age”, 18, 30)—&gt;age not between 18 and 30</td>
</tr>
<tr>
<td align="center">like</td>
<td align="center">LIKE ‘%值%’</td>
<td align="center">like(“name”, “王”)—&gt;name like ‘%王%’</td>
</tr>
<tr>
<td align="center">notLike</td>
<td align="center">NOT LIKE ‘%值%’</td>
<td align="center">notLike(“name”, “王”)—&gt;name not like ‘%王%’</td>
</tr>
<tr>
<td align="center">likeLeft</td>
<td align="center">LIKE ‘%值’</td>
<td align="center">likeLeft(“name”, “王”)—&gt;name like ‘%王’</td>
</tr>
<tr>
<td align="center">likeRight</td>
<td align="center">LIKE ‘值%’</td>
<td align="center">likeRight(“name”, “王”)—&gt;name like ‘王%’</td>
</tr>
<tr>
<td align="center">isNul</td>
<td align="center">字段 IS NULL</td>
<td align="center">isNull(“name”)—&gt;name is null</td>
</tr>
<tr>
<td align="center">isNotNull</td>
<td align="center">字段 IS NOT NULL</td>
<td align="center">isNotNull(“name”)—&gt;name is not null</td>
</tr>
<tr>
<td align="center">in</td>
<td align="center">字段 IN (value.get(0), value.get(1), …)</td>
<td align="center">in(“age”,{1,2,3})—&gt;age in (1,2,3)</td>
</tr>
<tr>
<td align="center">in</td>
<td align="center">字段 IN (v0, v1, …)</td>
<td align="center">in(“age”, 1, 2, 3)—&gt;age in (1,2,3)</td>
</tr>
<tr>
<td align="center">notIn</td>
<td align="center">字段 NOT IN (value.get(0), value.get(1), …)</td>
<td align="center">notIn(“age”,{1,2,3})—&gt;age not in (1,2,3)</td>
</tr>
<tr>
<td align="center">notIn</td>
<td align="center">字段 NOT IN (v0, v1, …)</td>
<td align="center">age not in (1,2,3)</td>
</tr>
<tr>
<td align="center">inSql</td>
<td align="center">字段 IN ( sql语句 )</td>
<td align="center">inSql( “ age “, “1 ,2,3,4,5,6”)—&gt;age in (1,2,3,4,5,6) ， inSql(“id”, “select id from table where id &lt; 3”)—&gt;id in (select id from table where id</td>
</tr>
<tr>
<td align="center">groupBy</td>
<td align="center">分组：GROUP BY 字段, …</td>
<td align="center">groupBy(“id”, “name”)—&gt;group by id,name</td>
</tr>
<tr>
<td align="center">orderByAsc</td>
<td align="center">排序：ORDER BY 字段, … ASC</td>
<td align="center">orderByAsc(“id”, “name”)—&gt;order by id ASC,name ASC</td>
</tr>
<tr>
<td align="center">orderByDesc</td>
<td align="center">排序：ORDER BY 字段, … DESC</td>
<td align="center">orderByDesc(“id”, “name”)—&gt;order by id DESC,name DESC</td>
</tr>
<tr>
<td align="center">orderBy</td>
<td align="center">排序：ORDER BY 字段, …</td>
<td align="center">orderBy(true, true, “id”, “name”)—&gt;order by id ASC,name ASC</td>
</tr>
<tr>
<td align="center">having</td>
<td align="center">HAVING ( sql语句 )</td>
<td align="center">having(“sum(age) &gt; 10”)—&gt;having sum(age) &gt; 10</td>
</tr>
<tr>
<td align="center">or</td>
<td align="center">拼接 OR 注意事项:主动调用or表示紧接着下一个方法不是用and连接!(不调用or则默认为使用and连接)</td>
<td align="center">eq(“id”,1).or().eq(“name”,“老王”)—&gt;id = 1 or name = ‘老王’</td>
</tr>
<tr>
<td align="center">and</td>
<td align="center">AND 嵌套</td>
<td align="center">and(i -&gt; i.eq(“name”, “李白”).ne(“status”, “活着”))—&gt;and (name = ‘李白’ and status &lt;&gt; ‘活着’)</td>
</tr>
<tr>
<td align="center">nested</td>
<td align="center">正常嵌套 不带 AND 或者 OR</td>
<td align="center">nested(i -&gt; i.eq(“name”, “李白”).ne(“status”, “活着”))—&gt;(name = ‘李白’ and status &lt;&gt; ‘活着’)</td>
</tr>
<tr>
<td align="center">last</td>
<td align="center">无视优化规则直接拼接到 sql 的最后 注意事项: 只能调用一次,多次调用以最后一次为准 有sql注入的风险,请谨慎使用</td>
<td align="center">last(“limit 1”)</td>
</tr>
<tr>
<td align="center">exists</td>
<td align="center">拼接 EXISTS ( sql语句 )</td>
<td align="center">exists(“select id from table where age = 1”)—&gt;exists (select id from table where age = 1)</td>
</tr>
<tr>
<td align="center">notExists</td>
<td align="center">拼接 NOT EXISTS ( sql语句 )</td>
<td align="center">notExists(“select id from table where age = 1”)—&gt;not exists (select id from table where age = 1)</td>
</tr>
</tbody></table>
<h4 id="QueryWrapper"><a href="#QueryWrapper" class="headerlink" title="QueryWrapper"></a>QueryWrapper</h4><p><strong>select【设置查询字段】</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">select(String... sqlSelect)</span><br><span class="line">select(Predicate&lt;TableFieldInfo&gt; predicate)</span><br><span class="line">select(Class&lt;T&gt; entityClass, Predicate&lt;TableFieldInfo&gt; predicate)</span><br></pre></td></tr></table></figure>

<p>例：select(“id”, “name”, “age”)</p>
<p>例:：select(i -&gt; i.getProperty().startsWith(“test”))</p>
<h4 id="UpdateWrapper"><a href="#UpdateWrapper" class="headerlink" title="UpdateWrapper"></a>UpdateWrapper</h4><p><strong>set</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">set(String column, Object val)</span><br><span class="line">set(<span class="type">boolean</span> condition, String column, Object val)</span><br></pre></td></tr></table></figure>

<p>例: set(“name”, “老李头”)</p>
<p>例: set(“name”, “”)—&gt;数据库字段值变为空字符串</p>
<p>例: set(“name”, null)—&gt;数据库字段值变为null</p>
<h3 id="Select"><a href="#Select" class="headerlink" title="Select"></a>Select</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 根据 ID 查询</span></span><br><span class="line">T <span class="title function_">selectById</span><span class="params">(Serializable id)</span>;</span><br><span class="line"><span class="comment">// 根据 entity 条件，查询一条记录</span></span><br><span class="line">T <span class="title function_">selectOne</span><span class="params">(<span class="meta">@Param(Constants.WRAPPER)</span> Wrapper&lt;T&gt; queryWrapper)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 查询（根据ID 批量查询）</span></span><br><span class="line">List&lt;T&gt; <span class="title function_">selectBatchIds</span><span class="params">(<span class="meta">@Param(Constants.COLLECTION)</span> Collection&lt;? extends Serializable&gt; idList)</span>;</span><br><span class="line"><span class="comment">// 根据 entity 条件，查询全部记录</span></span><br><span class="line">List&lt;T&gt; <span class="title function_">selectList</span><span class="params">(<span class="meta">@Param(Constants.WRAPPER)</span> Wrapper&lt;T&gt; queryWrapper)</span>;</span><br><span class="line"><span class="comment">// 查询（根据 columnMap 条件）</span></span><br><span class="line">List&lt;T&gt; <span class="title function_">selectByMap</span><span class="params">(<span class="meta">@Param(Constants.COLUMN_MAP)</span> Map&lt;String, Object&gt; columnMap)</span>;</span><br><span class="line"><span class="comment">// 根据 Wrapper 条件，查询全部记录</span></span><br><span class="line">List&lt;Map&lt;String, Object&gt;&gt; <span class="title function_">selectMaps</span><span class="params">(<span class="meta">@Param(Constants.WRAPPER)</span> Wrapper&lt;T&gt; queryWrapper)</span>;</span><br><span class="line"><span class="comment">// 根据 Wrapper 条件，查询全部记录。注意： 只返回第一个字段的值</span></span><br><span class="line">List&lt;Object&gt; <span class="title function_">selectObjs</span><span class="params">(<span class="meta">@Param(Constants.WRAPPER)</span> Wrapper&lt;T&gt; queryWrapper)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 根据 entity 条件，查询全部记录（并翻页）</span></span><br><span class="line">IPage&lt;T&gt; <span class="title function_">selectPage</span><span class="params">(IPage&lt;T&gt; page, <span class="meta">@Param(Constants.WRAPPER)</span> Wrapper&lt;T&gt; queryWrapper)</span>;</span><br><span class="line"><span class="comment">// 根据 Wrapper 条件，查询全部记录（并翻页）</span></span><br><span class="line">IPage&lt;Map&lt;String, Object&gt;&gt; <span class="title function_">selectMapsPage</span><span class="params">(IPage&lt;T&gt; page, <span class="meta">@Param(Constants.WRAPPER)</span> Wrapper&lt;T&gt; queryWrapper)</span>;</span><br><span class="line"><span class="comment">// 根据 Wrapper 条件，查询总记录数</span></span><br><span class="line">Integer <span class="title function_">selectCount</span><span class="params">(<span class="meta">@Param(Constants.WRAPPER)</span> Wrapper&lt;T&gt; queryWrapper)</span>;</span><br></pre></td></tr></table></figure>



<h4 id="查询所有不加条件"><a href="#查询所有不加条件" class="headerlink" title="查询所有不加条件"></a>查询所有不加条件</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//不加任何条件全部查询</span></span><br><span class="line">List&lt;User&gt; users = mapper.selectList(<span class="literal">null</span>);</span><br><span class="line">users.forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<h4 id="查询单条记录"><a href="#查询单条记录" class="headerlink" title="查询单条记录"></a>查询单条记录</h4><p>注意：seletOne返回的是一条实体记录，当出现多条时会报错</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">QueryWrapper</span> <span class="variable">wrapper</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>();</span><br><span class="line">wrapper.eq(<span class="string">&quot;id&quot;</span>,<span class="number">7</span>);</span><br><span class="line">System.out.println(mapper.selectOne(wrapper));</span><br></pre></td></tr></table></figure>

<h4 id="通过id查询"><a href="#通过id查询" class="headerlink" title="通过id查询"></a>通过id查询</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//查询单个id</span></span><br><span class="line"><span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> mapper.selectById(<span class="number">1</span>);</span><br><span class="line"><span class="comment">//批量操作查询多个id</span></span><br><span class="line">List&lt;User&gt; users = mapper.selectBatchIds(Arrays.asList(<span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>));</span><br></pre></td></tr></table></figure>

<h4 id="通过map查询"><a href="#通过map查询" class="headerlink" title="通过map查询"></a>通过map查询</h4><p>map只能做等值判断，逻辑判断需要使用wrapper</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//Map 只能做等值判断，逻辑判断需要使用 Wrapper 来处理</span></span><br><span class="line">Map&lt;String,Object&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">map.put(<span class="string">&quot;id&quot;</span>,<span class="number">7</span>);</span><br><span class="line">mapper.selectByMap(map).forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong>注意：map中的key对应的是数据库中的列名。例如数据库user_id，实体类是userId，这时map的key需要填写user_id</strong></p>
</blockquote>
<h4 id="单条件查询"><a href="#单条件查询" class="headerlink" title="单条件查询"></a>单条件查询</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//查询name为cb的用户</span></span><br><span class="line">QueryWrapper wrapper=<span class="keyword">new</span> <span class="title class_">QueryWrapper</span>();</span><br><span class="line">wrapper.eq(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;cb&quot;</span>);</span><br><span class="line">System.out.println(mapper.selectList(wrapper));</span><br></pre></td></tr></table></figure>

<h4 id="多条件查询"><a href="#多条件查询" class="headerlink" title="多条件查询"></a>多条件查询</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//多条件查询</span></span><br><span class="line"><span class="comment">//查询name为cb,age为18的用户</span></span><br><span class="line">QueryWrapper wrapper=<span class="keyword">new</span> <span class="title class_">QueryWrapper</span>();</span><br><span class="line">Map&lt;String,Object&gt; map=<span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">map.put(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;cb&quot;</span>);</span><br><span class="line">map.put(<span class="string">&quot;age&quot;</span>,<span class="number">18</span>);</span><br><span class="line">wrapper.allEq(map);</span><br><span class="line">System.out.println(mapper.selectList(wrapper));</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">wrapper.gt(<span class="string">&quot;age&quot;</span>,<span class="number">18</span>);  <span class="comment">//大于</span></span><br><span class="line">wrapper.ne(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;cb&quot;</span>); <span class="comment">//等于</span></span><br><span class="line">wrapper.ge(<span class="string">&quot;age&quot;</span>,<span class="number">18</span>); <span class="comment">//大于等于</span></span><br><span class="line">wrapper.lt(<span class="string">&quot;age&quot;</span>,<span class="number">18</span>);  <span class="comment">//小于</span></span><br><span class="line">wrapper.le(<span class="string">&quot;age&quot;</span>,<span class="number">18</span>);  <span class="comment">//小于等于</span></span><br></pre></td></tr></table></figure>

<h4 id="模糊查询"><a href="#模糊查询" class="headerlink" title="模糊查询"></a>模糊查询</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//模糊查询</span></span><br><span class="line">QueryWrapper wrapper=<span class="keyword">new</span> <span class="title class_">QueryWrapper</span>();</span><br><span class="line"><span class="comment">//相对于 like &#x27;%b%&#x27;</span></span><br><span class="line">wrapper.like(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;b&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//相当于 like &#x27;%b&#x27;</span></span><br><span class="line">wrapper.likeLeft(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;b&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//相当于 like &#x27;b%&#x27;</span></span><br><span class="line">wrapper.likeRight(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;b&quot;</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(mapper.selectList(wrapper));</span><br></pre></td></tr></table></figure>

<h4 id="子查询"><a href="#子查询" class="headerlink" title="子查询"></a>子查询</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">wrapper.inSql(<span class="string">&quot;id&quot;</span>,<span class="string">&quot;select id from user where id &lt; 10&quot;</span>);</span><br><span class="line">wrapper.inSql(<span class="string">&quot;age&quot;</span>,<span class="string">&quot;select age from user where age &gt; 3&quot;</span>);</span><br></pre></td></tr></table></figure>

<h4 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">wrapper.orderByDesc(<span class="string">&quot;age&quot;</span>);</span><br><span class="line">wrapper.orderByAsc(<span class="string">&quot;age&quot;</span>);</span><br><span class="line">wrapper.having(<span class="string">&quot;id &gt; 8&quot;</span>);</span><br></pre></td></tr></table></figure>

<h4 id="查询数量"><a href="#查询数量" class="headerlink" title="查询数量"></a>查询数量</h4><p>返回的是有几条数据</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">QueryWrapper</span> <span class="variable">wrapper</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>();</span><br><span class="line">wrapper.eq(<span class="string">&quot;id&quot;</span>,<span class="number">7</span>);</span><br><span class="line">System.out.println(mapper.selectCount(wrapper));</span><br></pre></td></tr></table></figure>

<h4 id="将查询结果封装到map"><a href="#将查询结果封装到map" class="headerlink" title="将查询结果封装到map"></a>将查询结果封装到map</h4><p>返回map而不是原来的对象</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">QueryWrapper</span> <span class="variable">wrapper</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>();</span><br><span class="line">wrapper.eq(<span class="string">&quot;id&quot;</span>,<span class="number">7</span>);</span><br><span class="line">mapper.selectMaps(wrapper).forEach(System.out::println);</span><br></pre></td></tr></table></figure>



<h4 id="分页查询"><a href="#分页查询" class="headerlink" title="分页查询"></a>分页查询</h4><p><strong>配置</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyBatisPlusConfig</span> &#123;</span><br><span class="line">    <span class="comment">// 最新版</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> MybatisPlusInterceptor <span class="title function_">mybatisPlusInterceptor</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">MybatisPlusInterceptor</span> <span class="variable">interceptor</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MybatisPlusInterceptor</span>();</span><br><span class="line">        interceptor.addInnerInterceptor(<span class="keyword">new</span> <span class="title class_">PaginationInnerInterceptor</span>(DbType.H2));</span><br><span class="line">        <span class="keyword">return</span> interceptor;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="mapper方法返回page对象"><a href="#mapper方法返回page对象" class="headerlink" title="mapper方法返回page对象"></a>mapper方法返回page对象</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//分页查询</span></span><br><span class="line"><span class="comment">//第一个参数是页数</span></span><br><span class="line"><span class="comment">//第二个参数每页的条数</span></span><br><span class="line">Page&lt;User&gt; page=<span class="keyword">new</span> <span class="title class_">Page</span>&lt;&gt;(<span class="number">1</span>,<span class="number">5</span>);</span><br><span class="line">Page&lt;User&gt; result = mapper.selectPage(page, <span class="literal">null</span>);</span><br><span class="line"><span class="comment">//每页条数</span></span><br><span class="line">System.out.println(result.getSize());</span><br><span class="line"><span class="comment">//总数</span></span><br><span class="line">System.out.println(result.getTotal());</span><br><span class="line"><span class="comment">//查询结果</span></span><br><span class="line">result.getRecords().forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<figure class="highlight tex"><table><tr><td class="code"><pre><span class="line">getCurrent 当前页</span><br><span class="line">getRecords 每页数据list集合</span><br><span class="line">getSize 每页显示记录数</span><br><span class="line">getTotal 总记录数</span><br><span class="line">getPages 总页数</span><br><span class="line"></span><br><span class="line">hasNext  是否有下一页</span><br><span class="line">hasPrevious  是否有上一页</span><br></pre></td></tr></table></figure>

<h4 id="mapper方法返回map集合"><a href="#mapper方法返回map集合" class="headerlink" title="mapper方法返回map集合"></a>mapper方法返回map集合</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Page&lt;Map&lt;String,Object&gt;&gt; page = <span class="keyword">new</span> <span class="title class_">Page</span>&lt;&gt;(<span class="number">1</span>,<span class="number">2</span>);</span><br><span class="line">mapper.selectMapsPage(page,<span class="literal">null</span>).getRecords().forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<h4 id="service方法返回page对象"><a href="#service方法返回page对象" class="headerlink" title="service方法返回page对象"></a>service方法返回page对象</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">IPage&lt;User&gt; ipage=<span class="keyword">new</span> <span class="title class_">Page</span>&lt;&gt;(<span class="number">1</span>,<span class="number">2</span>);</span><br><span class="line">IPage&lt;User&gt; page = userService.page(ipage);</span><br><span class="line">List&lt;User&gt; records = page.getRecords();</span><br><span class="line"></span><br><span class="line">System.out.println(records);</span><br><span class="line"><span class="comment">//总共数据的条数</span></span><br><span class="line">System.out.println(page.getTotal());</span><br><span class="line"><span class="comment">//总共数据的页数</span></span><br><span class="line">System.out.println(page.getPages());</span><br></pre></td></tr></table></figure>

<h3 id="xml自定义分页"><a href="#xml自定义分页" class="headerlink" title="xml自定义分页"></a>xml自定义分页</h3><h4 id="UserMapper"><a href="#UserMapper" class="headerlink" title="UserMapper"></a>UserMapper</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Repository</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;User&gt; &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;</span></span><br><span class="line"><span class="comment">     * 查询 : 根据年龄查询用户列表，分页显示</span></span><br><span class="line"><span class="comment">     * &lt;/p&gt;</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位(你可以继承Page实现自己的分页对象)</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> age 年龄</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 分页对象</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    IPage&lt;User&gt; <span class="title function_">getByAge</span><span class="params">(IPage iPage,Integer age)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>UserMapper.xml 等同于编写一个普通 list 查询，mybatis-plus 自动分页</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span> <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span> <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.blb.mybatisplus2.mapper.UserMapper&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getByAge&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">        select * from user1 where age=#&#123;age&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>UserServiceImpl.java 调用分页方法</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">xmlPage</span><span class="params">()</span>&#123;</span><br><span class="line">    IPage&lt;User&gt; byAge = userMapper.getByAge(<span class="keyword">new</span> <span class="title class_">Page</span>(<span class="number">1</span>, <span class="number">2</span>), <span class="number">18</span>);</span><br><span class="line">    List&lt;User&gt; records = byAge.getRecords();</span><br><span class="line">    System.out.println(records);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="自定义sql（多表关联）"><a href="#自定义sql（多表关联）" class="headerlink" title="自定义sql（多表关联）"></a>自定义sql（多表关联）</h3><h4 id="多表数据库"><a href="#多表数据库" class="headerlink" title="多表数据库"></a>多表数据库</h4><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">create  table  product(</span><br><span class="line">    category int ,</span><br><span class="line">    count int ,</span><br><span class="line">    description varchar(20),</span><br><span class="line">    userid bigint(100)</span><br><span class="line">)charset =utf8</span><br></pre></td></tr></table></figure>

<h4 id="ProductVO"><a href="#ProductVO" class="headerlink" title="ProductVO"></a>ProductVO</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProductVO</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Integer category;</span><br><span class="line">    <span class="keyword">private</span> Integer count;</span><br><span class="line">    <span class="keyword">private</span> String description;</span><br><span class="line">    <span class="keyword">private</span> Integer userId;</span><br><span class="line">    <span class="keyword">private</span> String userName;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="mapper接口"><a href="#mapper接口" class="headerlink" title="mapper接口"></a>mapper接口</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Repository</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;User&gt; &#123;</span><br><span class="line">    <span class="meta">@Select(&quot;select p.*,u.name username from product p,user u where u.id=p.userid and u.id=#&#123;id&#125;&quot;)</span></span><br><span class="line">    List&lt;ProductVO&gt; <span class="title function_">productList</span><span class="params">(<span class="meta">@Param(&quot;id&quot;)</span> Integer id)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h3 id="执行-SQL-分析打印"><a href="#执行-SQL-分析打印" class="headerlink" title="执行 SQL 分析打印"></a>执行 SQL 分析打印</h3><h4 id="p6spy-依赖引入"><a href="#p6spy-依赖引入" class="headerlink" title="p6spy 依赖引入"></a>p6spy 依赖引入</h4><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>p6spy<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>p6spy<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.9.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="application-yml-配置"><a href="#application-yml-配置" class="headerlink" title="application.yml 配置"></a>application.yml 配置</h4><figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">datasource:</span></span><br><span class="line">    <span class="attr">driver-class-name:</span> <span class="string">com.p6spy.engine.spy.P6SpyDriver</span> <span class="comment">#com.mysql.cj.jdbc.Driver</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">jdbc:p6spy:mysql://localhost:3306/db?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">root</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">mybatis-plus:</span></span><br><span class="line">  <span class="attr">configuration:</span></span><br><span class="line">    <span class="attr">log-impl:</span> <span class="string">org.apache.ibatis.logging.stdout.StdOutImpl</span></span><br><span class="line">    <span class="attr">map-underscore-to-camel-case:</span> <span class="literal">true</span></span><br><span class="line">  <span class="attr">type-enums-package:</span> <span class="string">com.blb.mybatisplus2.enums</span></span><br><span class="line">  <span class="attr">global-config:</span></span><br><span class="line">    <span class="attr">db-config:</span></span><br><span class="line">      <span class="attr">logic-not-delete-value:</span> <span class="number">0</span></span><br><span class="line">      <span class="attr">logic-delete-value:</span> <span class="number">1</span></span><br><span class="line">      <span class="attr">id-type:</span> <span class="string">auto</span></span><br><span class="line">  <span class="attr">type-aliases-package:</span> <span class="string">com.ase.mybatis.entity</span></span><br><span class="line">  <span class="attr">mapper-locations:</span> <span class="string">classpath:/mapper/*.xml</span></span><br></pre></td></tr></table></figure>

<h4 id="spy-properties-配置："><a href="#spy-properties-配置：" class="headerlink" title="spy.properties 配置："></a>spy.properties 配置：</h4><figure class="highlight properties"><table><tr><td class="code"><pre><span class="line"><span class="comment">#3.2.1以上使用</span></span><br><span class="line"><span class="attr">modulelist</span>=<span class="string">com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory</span></span><br><span class="line"><span class="comment">#3.2.1以下使用或者不配置</span></span><br><span class="line"><span class="comment">#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory</span></span><br><span class="line"><span class="comment"># 自定义日志打印</span></span><br><span class="line"><span class="attr">logMessageFormat</span>=<span class="string">com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger</span></span><br><span class="line"><span class="comment">#日志输出到控制台</span></span><br><span class="line"><span class="attr">appender</span>=<span class="string">com.baomidou.mybatisplus.extension.p6spy.StdoutLogger</span></span><br><span class="line"><span class="comment"># 使用日志系统记录 sql</span></span><br><span class="line"><span class="comment">#appender=com.p6spy.engine.spy.appender.Slf4JLogger</span></span><br><span class="line"><span class="comment"># 设置 p6spy driver 代理</span></span><br><span class="line"><span class="attr">deregisterdrivers</span>=<span class="string">true</span></span><br><span class="line"><span class="comment"># 取消JDBC URL前缀</span></span><br><span class="line"><span class="attr">useprefix</span>=<span class="string">true</span></span><br><span class="line"><span class="comment"># 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.</span></span><br><span class="line"><span class="attr">excludecategories</span>=<span class="string">info,debug,result,commit,resultset</span></span><br><span class="line"><span class="comment"># 日期格式</span></span><br><span class="line"><span class="attr">dateformat</span>=<span class="string">yyyy-MM-dd HH:mm:ss</span></span><br><span class="line"><span class="comment"># 实际驱动可多个</span></span><br><span class="line"><span class="comment">#driverlist=org.h2.Driver</span></span><br><span class="line"><span class="comment"># 是否开启慢SQL记录</span></span><br><span class="line"><span class="attr">outagedetection</span>=<span class="string">true</span></span><br><span class="line"><span class="comment"># 慢SQL记录标准 2 秒</span></span><br><span class="line"><span class="attr">outagedetectioninterval</span>=<span class="string">2</span></span><br></pre></td></tr></table></figure>

<hr>
<h2 id="MyBatisPlus-代码生成器"><a href="#MyBatisPlus-代码生成器" class="headerlink" title="MyBatisPlus 代码生成器"></a>MyBatisPlus 代码生成器</h2><p><strong>【根据数据表自动生成实体类、Mapper、Service、ServiceImpl、Controller】</strong></p>
<h3 id="导入依赖"><a href="#导入依赖" class="headerlink" title="导入依赖"></a>导入依赖</h3><p><strong>pom.xml 导入 MyBatis Plus Generator</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-generator<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.4.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.velocity<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>velocity-engine-core<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>Velocity（默认）、Freemarker、Beetl</p>
</blockquote>
<h3 id="运行main方法"><a href="#运行main方法" class="headerlink" title="运行main方法"></a>运行main方法</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Main</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//创建generator对象</span></span><br><span class="line">        <span class="type">AutoGenerator</span> <span class="variable">autoGenerator</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">AutoGenerator</span>();</span><br><span class="line">        <span class="comment">//数据源</span></span><br><span class="line">        <span class="type">DataSourceConfig</span> <span class="variable">dataSourceConfig</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DataSourceConfig</span>();</span><br><span class="line">        dataSourceConfig.setDbType(DbType.MYSQL);</span><br><span class="line">        dataSourceConfig.setUrl(<span class="string">&quot;jdbc:mysql://localhost:3306/db?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC&quot;</span>);</span><br><span class="line">        dataSourceConfig.setUsername(<span class="string">&quot;root&quot;</span>);</span><br><span class="line">        dataSourceConfig.setPassword(<span class="string">&quot;root&quot;</span>);</span><br><span class="line">        dataSourceConfig.setDriverName(<span class="string">&quot;com.mysql.cj.jdbc.Driver&quot;</span>);</span><br><span class="line">        autoGenerator.setDataSource(dataSourceConfig);</span><br><span class="line">        <span class="comment">//全局配置</span></span><br><span class="line">        <span class="type">GlobalConfig</span> <span class="variable">globalConfig</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GlobalConfig</span>();</span><br><span class="line">        <span class="comment">//当前项目的绝对路径</span></span><br><span class="line">        globalConfig.setOutputDir(System.getProperty(<span class="string">&quot;user.dir&quot;</span>)+<span class="string">&quot;/src/main/java&quot;</span>);</span><br><span class="line">        globalConfig.setOpen(<span class="literal">false</span>);</span><br><span class="line">        globalConfig.setAuthor(<span class="string">&quot;dyk&quot;</span>);</span><br><span class="line">        <span class="comment">//去掉默认生成接口名字的I</span></span><br><span class="line">        globalConfig.setServiceName(<span class="string">&quot;%sService&quot;</span>);</span><br><span class="line">        autoGenerator.setGlobalConfig(globalConfig);</span><br><span class="line">        <span class="comment">//包信息</span></span><br><span class="line">        <span class="type">PackageConfig</span> <span class="variable">packageConfig</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">PackageConfig</span>();</span><br><span class="line">        packageConfig.setParent(<span class="string">&quot;com.blb.mybatisplus&quot;</span>);</span><br><span class="line">		<span class="comment">//packageConfig.setModuleName(&quot;generator&quot;);</span></span><br><span class="line">        packageConfig.setController(<span class="string">&quot;controller&quot;</span>);</span><br><span class="line">        packageConfig.setService(<span class="string">&quot;service&quot;</span>);</span><br><span class="line">        packageConfig.setServiceImpl(<span class="string">&quot;service.impl&quot;</span>);</span><br><span class="line">        packageConfig.setMapper(<span class="string">&quot;mapper&quot;</span>);</span><br><span class="line">        packageConfig.setEntity(<span class="string">&quot;entity&quot;</span>);</span><br><span class="line">        autoGenerator.setPackageInfo(packageConfig);</span><br><span class="line">        <span class="comment">//配置策略</span></span><br><span class="line">        <span class="type">StrategyConfig</span> <span class="variable">strategyConfig</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StrategyConfig</span>();</span><br><span class="line">        strategyConfig.setEntityLombokModel(<span class="literal">true</span>);</span><br><span class="line">        strategyConfig.setRestControllerStyle(<span class="literal">true</span>);</span><br><span class="line">        <span class="comment">//生成部分数据库里面的表对应的实体类</span></span><br><span class="line">        strategyConfig.setInclude(<span class="string">&quot;user&quot;</span>,<span class="string">&quot;product&quot;</span>);</span><br><span class="line">        strategyConfig.setNaming(NamingStrategy.underline_to_camel);</span><br><span class="line">        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);</span><br><span class="line">        autoGenerator.setStrategy(strategyConfig);</span><br><span class="line"></span><br><span class="line">        autoGenerator.execute();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="完整版"><a href="#完整版" class="headerlink" title="完整版"></a>完整版</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Main1</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">// 代码生成器</span></span><br><span class="line">        <span class="type">AutoGenerator</span>  <span class="variable">autoGenerator</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">AutoGenerator</span>();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 全局配置</span></span><br><span class="line">        <span class="type">GlobalConfig</span> <span class="variable">gc</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GlobalConfig</span>();</span><br><span class="line">        <span class="comment">//获得当前项目的路径</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">projectPath</span> <span class="operator">=</span> System.getProperty(<span class="string">&quot;user.dir&quot;</span>);</span><br><span class="line">        <span class="comment">//设置生成路径</span></span><br><span class="line">        gc.setOutputDir(projectPath + <span class="string">&quot;/src/main/java&quot;</span>);</span><br><span class="line">        <span class="comment">//作者</span></span><br><span class="line">        gc.setAuthor(<span class="string">&quot;dyk&quot;</span>);</span><br><span class="line">        <span class="comment">//代码生成后是不是要打开文件所在的文件夹</span></span><br><span class="line">        gc.setOpen(<span class="literal">false</span>);</span><br><span class="line">        <span class="comment">//生成实体属性 Swagger2 注解</span></span><br><span class="line">        <span class="comment">// gc.setSwagger2(true);</span></span><br><span class="line">        <span class="comment">//会在mapper.xml生成一个基础的&lt;ResultMap&gt; 映射所有的字段</span></span><br><span class="line">        gc.setBaseResultMap(<span class="literal">true</span>);</span><br><span class="line">        <span class="comment">//同文件生成覆盖</span></span><br><span class="line">        gc.setFileOverride(<span class="literal">true</span>);</span><br><span class="line">        <span class="comment">//实体类名直接用表名  %s=表名</span></span><br><span class="line">        gc.setEntityName(<span class="string">&quot;%s&quot;</span>);</span><br><span class="line">        <span class="comment">//mapper接口名</span></span><br><span class="line">        gc.setMapperName(<span class="string">&quot;%sMapper&quot;</span>);</span><br><span class="line">        <span class="comment">//mapper.xml文件名</span></span><br><span class="line">        gc.setXmlName(<span class="string">&quot;%sMapper&quot;</span>);</span><br><span class="line">        <span class="comment">//业务逻辑接口名</span></span><br><span class="line">        gc.setServiceName(<span class="string">&quot;%sService&quot;</span>);</span><br><span class="line">        <span class="comment">//业务逻辑实现类名</span></span><br><span class="line">        gc.setServiceImplName(<span class="string">&quot;%sServiceImpl&quot;</span>);</span><br><span class="line">        <span class="comment">//将全局配置设置到 AutoGenerator</span></span><br><span class="line">        autoGenerator.setGlobalConfig(gc);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//数据源</span></span><br><span class="line">        <span class="type">DataSourceConfig</span> <span class="variable">dsc</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DataSourceConfig</span>();</span><br><span class="line">        <span class="comment">//设置数据库类型</span></span><br><span class="line">        dsc.setDbType(DbType.MYSQL);</span><br><span class="line">        <span class="comment">//连接的url</span></span><br><span class="line">        dsc.setUrl(<span class="string">&quot;jdbc:mysql://localhost:3306/db3?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC&quot;</span>);</span><br><span class="line">        <span class="comment">//数据库用户名</span></span><br><span class="line">        dsc.setUsername(<span class="string">&quot;root&quot;</span>);</span><br><span class="line">        <span class="comment">//数据库密码</span></span><br><span class="line">        dsc.setPassword(<span class="string">&quot;123456&quot;</span>);</span><br><span class="line">        <span class="comment">//数据库驱动</span></span><br><span class="line">        dsc.setDriverName(<span class="string">&quot;com.mysql.cj.jdbc.Driver&quot;</span>);</span><br><span class="line">        <span class="comment">//将数据源配置设置到 AutoGenerator</span></span><br><span class="line">        autoGenerator.setDataSource(dsc);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//包信息</span></span><br><span class="line">        <span class="type">PackageConfig</span> <span class="variable">pc</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">PackageConfig</span>();</span><br><span class="line">        <span class="comment">//包名</span></span><br><span class="line">        pc.setParent(<span class="string">&quot;com.blb&quot;</span>);</span><br><span class="line">        <span class="comment">//设置模块名</span></span><br><span class="line"><span class="comment">//        pc.setModuleName(&quot;generator&quot;);</span></span><br><span class="line">        pc.setController(<span class="string">&quot;controller&quot;</span>);</span><br><span class="line">        pc.setService(<span class="string">&quot;service&quot;</span>);</span><br><span class="line">        pc.setServiceImpl(<span class="string">&quot;service.impl&quot;</span>);</span><br><span class="line">        pc.setMapper(<span class="string">&quot;mapper&quot;</span>);</span><br><span class="line">        pc.setEntity(<span class="string">&quot;entity&quot;</span>);</span><br><span class="line">        autoGenerator.setPackageInfo(pc);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//配置策略</span></span><br><span class="line">        <span class="type">StrategyConfig</span> <span class="variable">strategyConfig</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StrategyConfig</span>();</span><br><span class="line">        <span class="comment">//表名的生成策略:下划线转驼峰</span></span><br><span class="line">        strategyConfig.setNaming(NamingStrategy.underline_to_camel);</span><br><span class="line">        <span class="comment">//列名的生成策略：下划线转驼峰</span></span><br><span class="line">        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);</span><br><span class="line">        <span class="comment">//支持lombok注解</span></span><br><span class="line">        strategyConfig.setEntityLombokModel(<span class="literal">true</span>);</span><br><span class="line">        <span class="comment">//在controller类上是否生成@Restcontroller</span></span><br><span class="line">        strategyConfig.setRestControllerStyle(<span class="literal">true</span>);</span><br><span class="line">        <span class="comment">//生成部分数据库里面的表对应的实体类，生成的表名</span></span><br><span class="line">        strategyConfig.setInclude(<span class="string">&quot;user&quot;</span>,<span class="string">&quot;product&quot;</span>);</span><br><span class="line">        <span class="comment">//按前缀生成表</span></span><br><span class="line">        <span class="comment">//strategyConfig.setLikeTable(&quot;tbl_&quot;);</span></span><br><span class="line">        <span class="comment">//设置表替换前缀</span></span><br><span class="line">        <span class="comment">//strategyConfig.setTablePrefix(&quot;tbl_&quot;);</span></span><br><span class="line">        autoGenerator.setStrategy(strategyConfig);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 自定义配置</span></span><br><span class="line">        <span class="type">InjectionConfig</span> <span class="variable">cfg</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">InjectionConfig</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">initMap</span><span class="params">()</span> &#123;</span><br><span class="line">                <span class="comment">// to do nothing</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 模板引擎是 velocity</span></span><br><span class="line">         <span class="type">String</span> <span class="variable">templatePath</span> <span class="operator">=</span> <span class="string">&quot;/templates/mapper.xml.vm&quot;</span>;</span><br><span class="line">        <span class="comment">// 自定义输出配置</span></span><br><span class="line">        List&lt;FileOutConfig&gt; focList = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">        <span class="comment">// 自定义配置会被优先输出</span></span><br><span class="line">        focList.add(<span class="keyword">new</span> <span class="title class_">FileOutConfig</span>(templatePath) &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> String <span class="title function_">outputFile</span><span class="params">(TableInfo tableInfo)</span> &#123;</span><br><span class="line">                <span class="comment">// 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！</span></span><br><span class="line">                <span class="keyword">return</span> projectPath + <span class="string">&quot;/src/main/resources/mapper/&quot;</span> + pc.getModuleName()</span><br><span class="line">                        + <span class="string">&quot;/&quot;</span> + tableInfo.getEntityName() + <span class="string">&quot;Mapper&quot;</span> + StringPool.DOT_XML;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        cfg.setFileOutConfigList(focList);</span><br><span class="line">        autoGenerator.setCfg(cfg);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 配置模板</span></span><br><span class="line">        <span class="type">TemplateConfig</span> <span class="variable">templateConfig</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TemplateConfig</span>();</span><br><span class="line">        <span class="comment">//让已有的xml生成置空</span></span><br><span class="line">        templateConfig.setXml(<span class="literal">null</span>);</span><br><span class="line">        autoGenerator.setTemplate(templateConfig);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//执行生成</span></span><br><span class="line">        autoGenerator.execute();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io">PaulGeorge</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io/posts/51171/">https://curry3035.gitee.io/posts/51171/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://curry3035.gitee.io" target="_blank">Celts</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/MyBatis/">MyBatis</a></div><div class="post_share"><div class="social-share" data-image="/img/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/53148/" title="实践一下--JWT"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">实践一下--JWT</div></div></a></div><div class="next-post pull-right"><a href="/posts/38677/" title="每日一面--数据库连接池"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">每日一面--数据库连接池</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/56080/" title="每日一面--MyBatis"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-07-23</div><div class="title">每日一面--MyBatis</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">PaulGeorge</div><div class="author-info__description">很多事情就像是旅行一样，当你决定要出发的时候，最困难的那部分其实就已经完成了</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/PaulGeorge123"><i class="fab fa-github"></i><span>GitHub URL</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/PaulGeorge123" target="_blank" title="Github"><i class="fab fa-github"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#MyBatisPlus-%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">MyBatisPlus  简介</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%89%B9%E6%80%A7"><span class="toc-number">1.1.</span> <span class="toc-text">特性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A1%86%E6%9E%B6%E7%BB%93%E6%9E%84"><span class="toc-number">1.2.</span> <span class="toc-text">框架结构</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#MyBatisPlus-%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8"><span class="toc-number">2.</span> <span class="toc-text">MyBatisPlus  快速入门</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%AE%80%E5%8D%95%E7%9A%84-Demo-%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.1.</span> <span class="toc-text">简单的 Demo 实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E5%BA%93%E4%B8%AD%E5%88%9B%E5%BB%BA-User-%E8%A1%A8"><span class="toc-number">2.1.1.</span> <span class="toc-text">数据库中创建 User 表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0-mybatis-plus-%E4%BE%9D%E8%B5%96"><span class="toc-number">2.1.2.</span> <span class="toc-text">添加 mybatis-plus 依赖</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BC%96%E5%86%99-application-yml-%E6%96%87%E4%BB%B6"><span class="toc-number">2.1.3.</span> <span class="toc-text">编写 application.yml 文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BD%93%E7%B1%BB"><span class="toc-number">2.1.4.</span> <span class="toc-text">创建实体类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA-Mapper-%E6%8E%A5%E5%8F%A3"><span class="toc-number">2.1.5.</span> <span class="toc-text">创建 Mapper 接口</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0%E6%89%AB%E6%8F%8F%E6%B3%A8%E8%A7%A3"><span class="toc-number">2.1.6.</span> <span class="toc-text">添加扫描注解</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BC%96%E5%86%99%E6%B5%8B%E8%AF%95%E7%B1%BB"><span class="toc-number">2.1.7.</span> <span class="toc-text">编写测试类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#service%E6%8E%A5%E5%8F%A3"><span class="toc-number">2.1.8.</span> <span class="toc-text">service接口</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#service%E5%AE%9E%E7%8E%B0%E7%B1%BB"><span class="toc-number">2.1.9.</span> <span class="toc-text">service实现类</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3"><span class="toc-number">2.2.</span> <span class="toc-text">常用注解</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#TableName"><span class="toc-number">2.2.1.</span> <span class="toc-text">@TableName</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#TableId"><span class="toc-number">2.2.2.</span> <span class="toc-text">@TableId</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#TableField"><span class="toc-number">2.2.3.</span> <span class="toc-text">@TableField</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Version"><span class="toc-number">2.2.4.</span> <span class="toc-text">@Version</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#EnumValue"><span class="toc-number">2.2.5.</span> <span class="toc-text">@EnumValue</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#TableLogic"><span class="toc-number">2.2.6.</span> <span class="toc-text">@TableLogic</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#OrderBy"><span class="toc-number">2.2.7.</span> <span class="toc-text">@OrderBy</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9D%A1%E4%BB%B6%E6%9E%84%E9%80%A0%E5%99%A8"><span class="toc-number">2.3.</span> <span class="toc-text">条件构造器</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#wrapper"><span class="toc-number">2.3.1.</span> <span class="toc-text">wrapper</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#QueryWrapper"><span class="toc-number">2.3.2.</span> <span class="toc-text">QueryWrapper</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#UpdateWrapper"><span class="toc-number">2.3.3.</span> <span class="toc-text">UpdateWrapper</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Select"><span class="toc-number">2.4.</span> <span class="toc-text">Select</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E6%89%80%E6%9C%89%E4%B8%8D%E5%8A%A0%E6%9D%A1%E4%BB%B6"><span class="toc-number">2.4.1.</span> <span class="toc-text">查询所有不加条件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E5%8D%95%E6%9D%A1%E8%AE%B0%E5%BD%95"><span class="toc-number">2.4.2.</span> <span class="toc-text">查询单条记录</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%80%9A%E8%BF%87id%E6%9F%A5%E8%AF%A2"><span class="toc-number">2.4.3.</span> <span class="toc-text">通过id查询</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%80%9A%E8%BF%87map%E6%9F%A5%E8%AF%A2"><span class="toc-number">2.4.4.</span> <span class="toc-text">通过map查询</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8D%95%E6%9D%A1%E4%BB%B6%E6%9F%A5%E8%AF%A2"><span class="toc-number">2.4.5.</span> <span class="toc-text">单条件查询</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A4%9A%E6%9D%A1%E4%BB%B6%E6%9F%A5%E8%AF%A2"><span class="toc-number">2.4.6.</span> <span class="toc-text">多条件查询</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A8%A1%E7%B3%8A%E6%9F%A5%E8%AF%A2"><span class="toc-number">2.4.7.</span> <span class="toc-text">模糊查询</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%90%E6%9F%A5%E8%AF%A2"><span class="toc-number">2.4.8.</span> <span class="toc-text">子查询</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8E%92%E5%BA%8F"><span class="toc-number">2.4.9.</span> <span class="toc-text">排序</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E6%95%B0%E9%87%8F"><span class="toc-number">2.4.10.</span> <span class="toc-text">查询数量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B0%86%E6%9F%A5%E8%AF%A2%E7%BB%93%E6%9E%9C%E5%B0%81%E8%A3%85%E5%88%B0map"><span class="toc-number">2.4.11.</span> <span class="toc-text">将查询结果封装到map</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%86%E9%A1%B5%E6%9F%A5%E8%AF%A2"><span class="toc-number">2.4.12.</span> <span class="toc-text">分页查询</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#mapper%E6%96%B9%E6%B3%95%E8%BF%94%E5%9B%9Epage%E5%AF%B9%E8%B1%A1"><span class="toc-number">2.4.13.</span> <span class="toc-text">mapper方法返回page对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#mapper%E6%96%B9%E6%B3%95%E8%BF%94%E5%9B%9Emap%E9%9B%86%E5%90%88"><span class="toc-number">2.4.14.</span> <span class="toc-text">mapper方法返回map集合</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#service%E6%96%B9%E6%B3%95%E8%BF%94%E5%9B%9Epage%E5%AF%B9%E8%B1%A1"><span class="toc-number">2.4.15.</span> <span class="toc-text">service方法返回page对象</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#xml%E8%87%AA%E5%AE%9A%E4%B9%89%E5%88%86%E9%A1%B5"><span class="toc-number">2.5.</span> <span class="toc-text">xml自定义分页</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#UserMapper"><span class="toc-number">2.5.1.</span> <span class="toc-text">UserMapper</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89sql%EF%BC%88%E5%A4%9A%E8%A1%A8%E5%85%B3%E8%81%94%EF%BC%89"><span class="toc-number">2.6.</span> <span class="toc-text">自定义sql（多表关联）</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A4%9A%E8%A1%A8%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="toc-number">2.6.1.</span> <span class="toc-text">多表数据库</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ProductVO"><span class="toc-number">2.6.2.</span> <span class="toc-text">ProductVO</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#mapper%E6%8E%A5%E5%8F%A3"><span class="toc-number">2.6.3.</span> <span class="toc-text">mapper接口</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%A7%E8%A1%8C-SQL-%E5%88%86%E6%9E%90%E6%89%93%E5%8D%B0"><span class="toc-number">2.7.</span> <span class="toc-text">执行 SQL 分析打印</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#p6spy-%E4%BE%9D%E8%B5%96%E5%BC%95%E5%85%A5"><span class="toc-number">2.7.1.</span> <span class="toc-text">p6spy 依赖引入</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#application-yml-%E9%85%8D%E7%BD%AE"><span class="toc-number">2.7.2.</span> <span class="toc-text">application.yml 配置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#spy-properties-%E9%85%8D%E7%BD%AE%EF%BC%9A"><span class="toc-number">2.7.3.</span> <span class="toc-text">spy.properties 配置：</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#MyBatisPlus-%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90%E5%99%A8"><span class="toc-number">3.</span> <span class="toc-text">MyBatisPlus 代码生成器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%BC%E5%85%A5%E4%BE%9D%E8%B5%96"><span class="toc-number">3.1.</span> <span class="toc-text">导入依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E8%A1%8Cmain%E6%96%B9%E6%B3%95"><span class="toc-number">3.2.</span> <span class="toc-text">运行main方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%8C%E6%95%B4%E7%89%88"><span class="toc-number">3.2.1.</span> <span class="toc-text">完整版</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/47231/" title="POI读取Excel问题">POI读取Excel问题</a><time datetime="2023-04-11T01:00:00.000Z" title="发表于 2023-04-11 09:00:00">2023-04-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/8422/" title="Excel大文件的上传">Excel大文件的上传</a><time datetime="2023-04-10T01:00:00.000Z" title="发表于 2023-04-10 09:00:00">2023-04-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/55119/" title="每日一面--Files工具类">每日一面--Files工具类</a><time datetime="2023-01-01T01:00:00.000Z" title="发表于 2023-01-01 09:00:00">2023-01-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/34600/" title="面试一下--JUC入门">面试一下--JUC入门</a><time datetime="2022-09-10T01:00:00.000Z" title="发表于 2022-09-10 09:00:00">2022-09-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/16284/" title="每日一面--字符流和字节流">每日一面--字符流和字节流</a><time datetime="2022-07-01T01:00:00.000Z" title="发表于 2022-07-01 09:00:00">2022-07-01</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By PaulGeorge</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>